package com.aichat.ai_chatbackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.aichat.ai_chatbackend.model.entity.ChatMessage;
import com.aichat.ai_chatbackend.service.ChatMessageService;
import com.aichat.ai_chatbackend.mapper.ChatMessageMapper;
import org.springframework.stereotype.Service;

import java.util.List;

/**
* @author yuppie
* @description 针对表【chat_message(聊天消息表)】的数据库操作Service实现
* @createDate 2025-07-13 14:40:37
*/
@Service
public class ChatMessageServiceImpl extends ServiceImpl<ChatMessageMapper, ChatMessage>
    implements ChatMessageService{

    @Override
    public List<ChatMessage> getRecentMessages(String sessionId, int limit) {
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("session_id", sessionId)
                   .eq("is_deleted", 0)
                   .orderByDesc("timestamp")
                   .last("LIMIT " + limit);
        
        List<ChatMessage> messages = this.list(queryWrapper);
        
        // 将消息按时间正序排列（从旧到新）
        messages.sort((a, b) -> a.getTimestamp().compareTo(b.getTimestamp()));
        
        return messages;
    }

    @Override
    public int getMessageCount(String sessionId) {
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("session_id", sessionId)
                   .eq("is_deleted", 0);
        
        return Math.toIntExact(this.count(queryWrapper));
    }

    @Override
    public List<ChatMessage> getBySessionId(String sessionId) {
        QueryWrapper<ChatMessage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("session_id", sessionId)
                   .eq("is_deleted", 0)
                   .orderByAsc("timestamp");
        
        return this.list(queryWrapper);
    }
}




